<?php

namespace Module\DyAi\Util;

use ModStart\Core\Assets\AssetsUtil;
use ModStart\Core\Dao\ModelUtil;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Module\DyAi\Model\DyAiCategory;
use Module\DyAi\Model\DownContent;
use Module\DyAi\Model\DyAiKeysugg;
use Module\DyAi\Model\DyAiZhuanji;
use Module\DyAi\Type\KeysuggStatus;

class DyAiKeysuggUtil
{
    public static function get($id)
    {
        return ModelUtil::get(DyAiKeysugg::class, $id);
    }

    public static function update($id, $data)
    {
        return ModelUtil::update(DyAiKeysugg::class, $id, $data);
    }

    public static function all()
    {
        return ModelUtil::all(DyAiKeysugg::class, [], ['*'], ['sort', 'asc']);
    }

    public static function latest($limit = 5)
    {
        return ModelUtil::model(DyAiKeysugg::class)
            ->orderBy('id', 'desc')
            ->limit($limit)->get()->toArray();
    }

    public static function buildRecord($record)
    {
        $record['cover'] = AssetsUtil::fixFull($record['cover']);
        return $record;
    }

    public static function buildRecords($records)
    {
        foreach ($records as $k => $v) {
            $records[$k] = self::buildRecord($v);
        }
        return $records;
    }

    public static function updateStatus($ids, $status)
    {
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        if (empty($ids)) {
            return;
        }
        ModelUtil::model(DyAiKeysugg::class)->whereIn('id', $ids)->update(['status' => $status]);
    }

    public static function addZhuanji($ids)
    {
		if (!is_array($ids)) {
            $ids = [$ids];
        }
        if (empty($ids)) {
            return;
        }
		$results = DyAiKeysugg::whereIn('id', $ids)->get();
		$all_dep = DyAiCategory::all();
		foreach($results as $k=>$r){
			$data = [];
			$zj = DyAiZhuanji::where('suggid', $r['id'])->get();
			if(count($zj)==0){
				$catid = 0;$typeid = 0;
				$keyword = $r['keyword'];
				$sugg = json_decode($r['sugg_json'],true);
				if(count($sugg['s'])>0){
					$s = $sugg['s'];  
					// 自定义排序函数，按照字符串长度降序排序  
					usort($s, function($a, $b) {
						return strlen($b) - strlen($a);  
					});
					  
					// 取前三条最长的字符串  
					$longestStrings = array_slice($s, 0, 3);  
					$dep_json = [];
					foreach($all_dep as $a_i=>$dep){
                        //if($dep['id'] != 3)continue;
						$downs = DownContent::whereRaw("ai_json LIKE ?", ["%\"{$keyword}\"%"])->where("cat_type",1)->where("categoryId",$dep['id'])
						->take(100) // 只取前 100 条记录  where("ai_json",'LIKE','%'.$keyword.'%')
                        ->get(['id','categoryId','down_id'])->toArray();
                        $down_ids = [];
                        foreach ($downs as $dk=>$d){
                            $down_ids[] = $d['down_id'];
                        }
						$dep_json[$dep['id']] = ['thumb'=>'','zj_banner'=>'','desc'=>'','content'=>'','ids'=>$down_ids];
					}
					// 拼接字符串  
					$combinedString = implode('_', $longestStrings);
					$data = ['suggid'=>$r['id'],'sub_title'=>$keyword,'title'=>$combinedString,'tag'=>$keyword,'keywords'=>str_replace('_',',',$combinedString),'dep_json'=>json_encode($dep_json)];
					ModelUtil::insert(DyAiZhuanji::class,$data);
				}
			}
		}
		self::updateStatus($ids, KeysuggStatus::ADOPT);
    }
}
